<template>
  <div class="container">
    <div class="header">
      <div class="header-left">
        <a href="javascript:;" @click="goBack" class="iconfont back-icon"
          >&#xe624;</a
        >
      </div>
      <div class="title">在线举报</div>
    </div>

    <div class="content">
      <div class="header_tab-bar">
        <div
          class="tab1"
          :class="[report_data.isreal_name == 1 ? 'active' : '']"
          v-on:click="report_data.isreal_name = 1"
        >
          实名举报
        </div>
        <div
          class="tab2"
          :class="[report_data.isreal_name != 1 ? 'active' : '']"
          v-on:click="report_data.isreal_name = 0"
        >
          匿名举报
        </div>
      </div>

      <div class="personal form-card" v-if="report_data.isreal_name">
        <div class="form-card-title">个人消息</div>
        <div class="form-card-content">
          <div class="input-group">
            <label for="">姓名</label>
            <input
              type="text"
              placeholder="请输入姓名"
              v-model="report_data.name"
            />
          </div>
          <div class="input-group">
            <label for="">身份证号</label>
            <input
              type="text"
              placeholder="请输入身份证号"
              v-model="report_data.idcard"
            />
          </div>
          <div class="input-group">
            <label for="">联系方式</label>
            <input
              type="tel"
              placeholder="请输入联系电话"
              @input="change"
              @change="change"
              v-model="report_data.phonenumber"
              maxlength="12"
            />
          </div>
          <div class="input-group">
            <label for="">联系地址</label>
            <input
              type="text"
              placeholder="请输入详细地址"
              v-model="report_data.detailed_address"
            />
          </div>
        </div>
      </div>
      <div class="report-content form-card">
        <div class="form-card-title">举报内容</div>
        <div class="form-card-content">
          <div class="input-group">
            <label for="">标题</label>
            <input
              type="text"
              placeholder="请输入标题"
              v-model="report_data.title"
            />
          </div>
          <!-- <div class="input-group">
            <label for="">问题类别</label>
            <input type="text" placeholder="请选择">
            <input
              type="text"
              placeholder="请选择"
              v-model="message"
              @click="ShouPup"
            />
          </div> -->
          <div class="input-group">
            <label for="">被举报单位</label>
            <input
              type="text"
              placeholder="请输入举报单位名称"
              v-model="report_data.company_title"
            />
          </div>
          <div class="input-group">
            <label for="">单位地址</label>
            <input
              type="text"
              placeholder="请输入举报单位所在地址"
              v-model="report_data.company_address"
            />
          </div>
          <div class="input-group input-big-box">
            <label for="">主要问题</label>
            <textarea
              type="text"
              placeholder="请输入问题内容"
              rows="3"
              v-model="report_data.content"
            >
            </textarea>
          </div>
          <div class="input-group input-big-box">
            <label for="">附件</label>
            <div class="file">
              <span v-for="(img, index) in img_tem" :key="index">
                <!-- <img :src="img.url" preview="1" :preview-text="img.title"
                  src="http://192.168.0.165/uploads-cache/1564138751.png"
                  alt=""
                /> -->
                <img
                  :src="img.url"
                  preview="1"
                  :preview-text="img.title"
                  alt=""
                />
                <s @click="delImg(index)"></s>
              </span>
              <span class="inputfile">
                <input
                  @change="upavatarimg"
                  type="file"
                  name=""
                  id=""
                  ref="file"
                  value="图片上传预览"
                />
              </span>
            </div>
            <div class="progress" v-if="upload_progress > 0">
              <mt-progress
                :value="upload_progress"
                :bar-height="2"
              ></mt-progress>
            </div>
          </div>
        </div>
      </div>
      <div class="msg-test form-card">
        <div class="form-card-title">短信验证</div>
        <div class="form-card-content">
          <div class="input-group">
            <label for="">手机号</label>
            <input
              type="tel"
              class="min-input"
              placeholder="请输入手机号"
              @input="change"
              @change="change"
              maxlength="12"
              v-model="report_data.mobile"
            />
            <button v-if="countdown > 0" disabled>
              <span v-text="countdown"></span>s重新获取
            </button>
            <button @click="getCaptcha" v-if="countdown <= 0">
              获取验证码
            </button>
          </div>
          <div class="input-group">
            <label for="">验证码</label>
            <input
              type="text"
              placeholder="请输入验证码"
              v-model="report_data.verification_code"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="footer_btn">
      <!-- <router-link tag="button" :to="'/inform/form'">提交 </router-link> -->
      <button @click="formSubmit">提交</button>
    </div>

    <mt-popup
      v-model="popupVisible"
      popup-transition="popup-fade"
      closeOnClickModal="true"
      position="bottom"
    >
      <mt-picker :slots="slots" @change="onValuesChange" showToolbar>
        <div class="picker-toolbar-title">
          <div class="usi-btn-cancel" @click="popupVisible = !popupVisible">
            取消
          </div>
          <div class="">选择类别</div>
          <div class="usi-btn-sure" @click="popupVisible = !popupVisible">
            确定
          </div>
        </div>
      </mt-picker>
    </mt-popup>
  </div>
</template>

            
<script>
import { Toast, Indicator } from "mint-ui";
export default {
  name: "OnLineReport",
  data() {
    return {
      report_data: {
        isreal_name: 1,
        imgs: []
      },

      showToolbar: true,
      message: "选择类别",
      slots: [
        {
          values: ["苏州"]
        }
      ],
      popupVisible: false,
      upload_progress: 0,

      //图片上传
      img_tem: [
        // {
        //   url: require("@/assets/images/close.png"),
        //   title: ""
        // }
      ],

      imgType: {
        type: "image/gif, image/jpeg, image/png, image/jpg"
      }, //图片格式

      //验证码倒计时
      time_show: false,
      countdown: 0,
      timer: null
    };
  },
  created() {
    this.getToken();
  },
  beforeDestroy() {},
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    //选择问题类别
    ShouPup() {
      this.popupVisible = true;
    },
    //切换问题类别
    onValuesChange(picker, values) {
      this.message = values;
      if (values[0] > values[1]) {
        picker.setSlotValue(1, values[0]);
      }
    },
    //获取随机token
    getToken() {
      this.$axios
        .get("api/report/getToken")
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          console.log(error);
        });
    },
    //手机号码验证
    change(event) {
      let val = event.target.value;
      // 只能是正整数或空,可根据需求修改正则
      //item = e.target.value.replace(/[^\d]/g,'')
      if (/^[1-9]\d*$|^$/.test(val)) {
        this.oldNum = val;
      } else {
        event.target.value = this.oldNum || "";
      }
    },

    formSubmit() {
      //如果是实名
      let report_data = this.report_data;
      if (report_data.isreal_name == 1) {
        if (!report_data.name) {
          Toast("请输入姓名");
          return false;
        }

        if (!report_data.idcard) {
          Toast("请输入身份证号码");
          return false;
        }
        //精准身份证校验 (第三方js身份证验证库) 110101199003079593
        if (!this.validid.cnid(report_data.idcard)) {
          Toast("请输入正确的身份证号码");
          return false;
        }

        if (!report_data.phonenumber) {
          Toast("请输入联系方式");
          return false;
        }

        //电话校验 (包括手机)
        if (
          report_data.phonenumber &&
          !/^((0\d{2,3}\d{7,8})|(1[3584]\d{9}))$/.test(report_data.phonenumber)
        ) {
          Toast("请输入正确的联系方式");
          return false;
        }

        if (!report_data.detailed_address) {
          Toast("请输入详细地址");
          return false;
        }
      }

      if (!report_data.title) {
        Toast("请输入标题");
        return false;
      }

      if (!report_data.company_title) {
        Toast("请输入举报单位");
        return false;
      }
      if (!report_data.company_address) {
        Toast("请输入举报单位地址");
        return false;
      }
      if (!report_data.content) {
        Toast("请输入主要问题");
        return false;
      }

      if (!report_data.mobile) {
        Toast("请输入手机号");
        return false;
      }
      if (report_data.mobile && !/^(1[3584]\d{9})$/.test(report_data.mobile)) {
        Toast("请输入正确的手机号");
        return false;
      }

      if (!report_data.verification_code) {
        Toast("请输入验证码");
        return false;
      }

      Indicator.open();

      this.$axios
        .post("api/report/post", report_data)
        .then(res => {
          if (res.data.status == 0) {
            console.log(res.data.result.message instanceof Array);
            if (res.data.result.message instanceof Array) {
              Toast(res.data.result.message[0][0]);
              Indicator.close();
              return false;
            } else {
              Toast(res.data.result.message);
              Indicator.close();
              return false;
            }
          }
          this.$router.push({
            name: "reportsuccessify",
            query: {
              view_number: res.data.result.view_number,
              view_password: res.data.result.view_password
            }
          });
          Indicator.close();
          console.log(res);
        })
        .catch(error => {
          console.log(error);
          alert(JSON.stringify(error));
          Indicator.close();
        });
    },

    //获取验证码
    getCaptcha() {
      this.$axios
        .post("api/report/getcaptcha", { mobile: this.report_data.mobile })
        .then(res => {
          //抛出异常
          if (res.data.status == 0) {
            console.log(res.data.result.message instanceof Array);
            if (res.data.result.message instanceof Array) {
              Toast(res.data.result.message[0][0]);
              return false;
            }
          }
          let TIME_COUNT = 60;
          //防止刷新页面重新获取 进行频繁请求短信
          if (res.data.status == -2) {
            Toast(res.data.result.message);
            TIME_COUNT = res.data.result.waiting;
          }
          //没有报错 启用倒计时
          this.time_show = false;

          if (!this.timer) {
            this.countdown = TIME_COUNT;
            this.time_show = false;
            this.timer = setInterval(() => {
              // console.log(this.countdown);
              if (this.countdown > 0 && this.countdown <= TIME_COUNT) {
                this.countdown--;
              } else {
                this.time_show = true;
                clearInterval(this.timer);
                this.timer = null;
              }
            }, 1000);
          }
        })
        .catch(error => {
          console.log(error.response);
          Indicator.close();
        });
    },

    //图片上传
    upavatarimg: function(e) {
      var _this = this;

      //加载中
      var avatarImg = e.target.files[0];
      var avatarImgsize = avatarImg.size;
      var avatarImgtype = avatarImg.type;
      // alert(avatarImgsize)
      //验证图片格式
      if (this.imgType.type.indexOf(avatarImgtype) == -1) {
        Toast("请选择正确的图片格式");
        return false;
      }
       else if (avatarImgsize > 10485760) {  //5M  5242880
        //验证图片大小 10M
        Toast("图片大小不能超过10M");
        return false;
      }
       else {
        Indicator.open();
        this.$refs.file.value = "";
        //清空file
        var avatarData = new FormData();
        avatarData.append("file", avatarImg); //图片

        //原生图片上传
        var xhr = new XMLHttpRequest();
        xhr.open("post", "api/report/uploader", true);
        xhr.upload.onprogress = progressFunction; //【上传进度调用方法实现】
        xhr.onload = uploadComplete; //请求完成
        xhr.onerror = uploadFailed; //请求失败
        xhr.onreadystatechange = function() {
          //当readyState变化时执行 （作为上传结果不可靠）
          // console.log(1111)
          // console.info(xhr.readyState, xhr.status, xhr.responseText);
          // if (xhr.readyState == 4 && xhr.status == 200) {
          //   var res = eval("(" + xhr.responseText + ")");
          //   console.log(res);
          //   _this.upload_progress = 0;
          //   let img = {
          //     url: res.result.url + "/" + res.result.imgs.file,
          //     title: ""
          //   };
          //   _this.img_tem.push(img); //显示用的
          //   _this.report_data.imgs.push(res.result.imgs.file); //提交到后台的
          //   Indicator.close(); //加载完成
          //   _this.$previewRefresh(); //刷新图片预览缓存
          // } else {
          //   Toast("上传超时,如果条件允许请使用数据网络上传！");
          //   Indicator.close(); //加载完成
          // }
        };
        //上传进度
        function progressFunction(evt) {
          // event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
          if (evt.lengthComputable) {
            //
            let complete = ((evt.loaded / evt.total) * 100) | 0;
            _this.upload_progress = complete;
          }
        }
        //上传成功响应
        function uploadComplete(evt) {
          //服务断接收完文件返回的结果
          console.log(evt.target.status);
          if (evt.target.readyState == 4 && evt.target.status == 200) {
            var res = eval("(" + evt.target.responseText + ")");
            console.log(res);
            _this.upload_progress = 0;

            let img = {
              url: res.result.url + "/" + res.result.imgs.file,
              title: ""
            };
            _this.img_tem.push(img); //显示用的
            _this.report_data.imgs.push(res.result.imgs.file); //提交到后台的

            Indicator.close(); //加载完成

            _this.$previewRefresh(); //刷新图片预览缓存
          } else {
            Toast("上传超时,如果条件允许请使用数据网络上传！");
            Indicator.close(); //加载完成
          }

          // Toast("上传成功！");
        }
        //上传失败
        function uploadFailed(evt) {
          Toast("上传超时,如果条件允许请使用数据网络上传！");
        }
        //开始发送
        xhr.send(avatarData);


        //向后台发送请求 提示：axios 需要安装插件  (axios上传会出现安卓部分手机非常慢的bug目前还没时间翻源码看原因)
        // _this.$axios
        //   .post(
        //     "api/report/uploader",
        //     avatarData, //data里面填入图片资源 avatarData，注意传值方式由后台定义
        //     {
        //       timeout:60000,
        //       headers: {
        //         "Content-Type": "multipart/form-data"
        //       },
        //       transformRequest: [
        //         function(data) {
        //           return data;
        //         }
        //       ],
        //       onUploadProgress: progressEvent => {
        //         //上传进度捕获
        //         let complete =
        //           ((progressEvent.loaded / progressEvent.total) * 100) | 0;

        //         _this.upload_progress = complete;

        //         // Indicator.open("正在上传 " + complete);
        //         // _this.data.uploadmessage = "上传 " + complete;
        //       }
        //     }
        //   )
        //   .then(function(res) {
        //     console.log(res.data);

        //     _this.upload_progress = 0;
        //     var img = {
        //       url: res.data.result.url + "/" + res.data.result.imgs.file,
        //       title: ""
        //     };
        //     _this.img_tem.push(img); //显示用的
        //     _this.report_data.imgs.push(res.data.result.imgs.file); //提交到后台的

        //     Indicator.close(); //加载完成

        //     _this.$previewRefresh(); //刷新图片预览缓存
        //   })
        //   .catch(function(err) {
        //     console.log(err);
        //     Toast("上传超时,请检查网络后重试！");
        //     // alert(JSON.stringify(err))
        //     Indicator.close();
        //   });
        
      }
    },
    delImg(index) {
      this.$delete(this.img_tem, index);
      this.$delete(this.report_data.imgs, index);
      this.$previewRefresh(); //刷新图片预览缓存
    }
  }
};
</script>

<style lang="stylus" scoped>
.container {
  height: 100%;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  height: 0.44rem;
  line-height: 0.44rem;
  background: #256ccb;
  color: #fff;

  .header-left {
    width: 0.4rem;

    .back-icon {
      display: block;
      text-align: center;
      font-size: 0.17rem;
      font-weight: bold;
      color: #fff;
    }
  }

  .title {
    width: 100%;
    text-align: center;
    margin-right: 0.33rem;
    font-size: 0.17rem;
    font-weight: bold;
  }
}

.content {
  margin-top: 0.44rem;
  padding-bottom: 1px; // 解决内部margin无效问题
  display: block;
  min-height: calc(80% - 0.4rem);
  background-color: #f2f2f2;

  .header_tab-bar {
    width: 100%;
    background-color: #fff;
    height: 0.42rem;

    >div {
      font-weight: bold;
      font-size: 16px;
      line-height: 0.4rem;
      border-bottom: 0.01rem solid #e3e8ef;
    }

    >div.active {
      color: #256ccb;
      border-bottom: 0.02rem solid #256ccb;
    }

    .tab1 {
      float: left;
      width: 50%;
      text-align: center;
    }

    .tab2 {
      float: right;
      width: 50%;
      text-align: center;
    }
  }

  .form-card {
    width: 100%;
    background-color: #ffffff;
    margin-bottom: 0.1rem;

    .form-card-title {
      width: 96%;
      margin-left: 4%;
      height: 0.45rem;
      line-height: 0.45rem;
      color: #e34e4e;
    }

    .form-card-content {
      width: 96%;
      margin-left: 4%;

      .input-group {
        border-top: 0.01rem solid #e3e8ef;
        height: 0.44rem;
        line-height: 0.44rem;

        label {
          display: inline-block;
          width: 23%;
        }

        input {
          display: inline-block;
          width: 73%;
          height: 0.42rem;
          line-height: 0.42rem;
          text-align: right;
        }
      }

      .input-big-box {
        height: auto;

        label {
          display: block;
          width: 100%;
        }

        textarea {
          width: 100%;
        }

        .file {
          span {
            width: 40px;
            height: 40px;
            margin-right: 10px;
            display: inline-block;
            position: relative;

            img {
              width: 40px;
              height: 40px;
              position: absolute;
              top: 4px;
              left: 0;
            }

            s {
              position: absolute;
              right: 0px;
              top: 0px;
              height: 10px;
              width: 10px;
              display: block;
              background: url('~@/assets/images/close.png') center center no-repeat;
              background-size: contain;
            }
          }

          .inputfile {
            width: 40px;
            height: 40px;
            display: inline-block;
            background: url('~@/assets/images/attachment.png') center center no-repeat;
            background-size: contain;
            position: relative;
            top: 4px;

            input {
              position: absolute;
              width: 100%;
              height: 100%;
              display: block;
              top: 0;
              left: 0;
              opacity: 0;
            }
          }
        }

        .progress {
          width: calc(100% - 4%);
        }
      }
    }
  }

  .msg-test {
    .form-card-content {
      .input-group {
        label {
          width: 15%;
        }

        input {
          text-align: left;
        }

        .min-input {
          width: 55%;
        }

        button {
          width: 24%;
          font-size: 0.12rem;
          display: inline-block;
          height: 0.22rem;
          border-radius: 0.25rem;
          border: 1px solid #256ccb;
          color: #256ccb;
          background: #fff;
        }

        button:disabled {
          color: #ccc;
          border: 1px solid #ccc;
        }
      }
    }
  }
}

.footer_btn {
  padding: 20px 0;

  button {
    font-size: 18px;
    width: 90%;
    border-radius: 30px;
    padding: 8px;
    background: #e95858;
    color: white;
    margin-left: 5%;
  }

  button:disabled {
    background: #ff9696;
  }
}

.mint-popup {
  width: 100%;

  .picker {
    width: 100%;
  }
}

.picker-toolbar-title {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  height: 40px;
  line-height: 40px;
  font-size: 16px;
}

.usi-btn-cancel, .usi-btn-sure {
  color: #FF6600;
}
</style>
